package com.yjc.drygoods.coupon.service.impl;

import com.xxl.job.core.handler.annotation.XxlJob;
import com.yjc.drygoods.coupon.entity.CouponHistoryEntity;
import com.yjc.drygoods.coupon.service.CouponHistoryService;
import com.yjc.drygoods.coupon.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.common.utils.PageUtils;
import com.yjc.common.utils.Query;

import com.yjc.drygoods.coupon.dao.CouponDao;
import com.yjc.drygoods.coupon.entity.CouponEntity;


@Service("couponService")
public class CouponServiceImpl extends ServiceImpl<CouponDao, CouponEntity> implements CouponService {

    @Autowired
    CouponHistoryService couponHistoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CouponEntity> page = this.page(
                new Query<CouponEntity>().getPage(params),
                new QueryWrapper<CouponEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 每天扫描优惠券表,更新优惠券状态
     */
    @XxlJob("updateCouponUseType")
    public void updateCouponUseType() {
        //当前时间
        Date date = new Date();
        List<CouponEntity> list = this.list(new QueryWrapper<CouponEntity>().lt("end_time", date));
        if (list != null && list.size() > 0) {
            List<CouponHistoryEntity> res = list.stream().map(item -> {
                CouponHistoryEntity couponHistoryEntity = new CouponHistoryEntity();
                couponHistoryEntity.setCouponId(item.getId());
                couponHistoryEntity.setUseType(2);
                return couponHistoryEntity;
            }).collect(Collectors.toList());
            couponHistoryService.updateMemberCouponUseType(res);
        }
    }

}